import ajax from "@/utils/ajax";
import { tableSelection, deleteConfirm } from "@/utils/elementui.js";
import axios from "axios";
export default {
  data() {
    return {
      organId: "",
      organOptions: [],
      permission: {
        add: false,
        modify: false,
        delete: false,
        bind_strategy: false,
        add_area_channel: false,
        delete_area_channel: false,
      },
      customerId: "",
      allSceneGroupTableData: [],
      SceneGroupTableData: [],
      tableIndex: 0,
      currentSceneGroup: null,
      SceneGroupId: null,

      isAddNew: true,
      // 新增组
      dialogSceneGroupVisible: false,
      rules: {
        sceneGroupName: [{ required: true, message: "组名称不能为空", trigger: "blur" }],
      },
      pojoSceneGroup: {
        organId: null,
        sceneGroupName: "",
      },
      // 区域和电器table
      SceneGroupAppliancesData: [],
      dialogAddAreaVisible: false,
      dialogAreaNodeCheck: [],
      multipleAreaAppSelection: [],
      Searchremark: "",
      ruleequipmenttype: 1,
      //区域
      areaData: [],
      areaid: "",
      proadvalue: [],
      oldproadvalue: [],
      prodlistdata: [],
      allprodlistdata: [],
      prodprops: {
        key: "id",
        label: "channelName",
      },
      renderFunc(h, option) {
        return <span title={option.channelName}>{option.channelName}</span>;
      },
      airOperationFlag: 2,
      AreaByOrgandata: [],
      ProbeChannelProps: {
        children: "children",
        label: "name",
        value: "id",
        checkStrictly: true,
      },
      userListdata: [],
      bindUserdata: [],
      Userprops: {
        key: "id",
        label: "name",
      },
      dialogBindUserVisible: false,
      userrenderFunc(h, option) {
        return <span title={option.name}>{option.name}</span>;
      },
      bindSceneGroupId: null,
      bindSceneGrouptitle: '',
    };
  },
  created() {
    this.customerId = this.$store.getters.customerId;
  },
  mounted() {
    this.$store.dispatch("actions/dynamicTitleAction", this.$route.meta.title);
    this.getOrganListData();
  },

  methods: {

    // 获取网点列表
    getOrganListData() {
      ajax.get({
        url: this.$API.getUserOrgan + this.$store.getters.user.id,
        success: (response) => {
          const resp = response.data;
          if (resp.length > 0) {
            this.organOptions = resp;
            this.organId = resp[0].id;
            this.getSceneGroupData();
            this.getOrganProbeListData();
            this.getAreaTreeByOrganId();
          } else {
            this.organOptions = [];
          }
        },
        error: (res) => {
          this.$message({
            message: res.message,
            type: "error",
          });
        },
      });
    },
    organChangeEvent() {
      this.getSceneGroupData();
      this.getOrganProbeListData();
      this.getAreaTreeByOrganId();
    },
    //通过网点获取区域列表
    getAreaTreeByOrganId() {
      ajax.get({
        url: this.$API.getAreaTreeByOrganId + this.organId,
        success: (response) => {
          this.areaid = "";
          this.AreaByOrgandata = response.data;
        },
        error: (res) => {
          //console.log(res)
          this.$message({
            message: res.message,
            type: "error",
          });
        },
      });
    },
    // 获取控制组的数据
    getSceneGroupData() {
      ajax.post({
        url: this.$API.getsceneGroupList + this.organId,
        success: (response) => {
          const resp = response.data;
          this.allSceneGroupTableData = resp;
          this.SceneGroupTableData = resp;
          if (resp.length > 0) {
            this.$nextTick(() => {
              let index = this.tableIndex;
              this.$refs.refSceneGroupTable.setCurrentRow(
                this.$refs.refSceneGroupTable.data[index]
              );
              this.currentSceneGroup = resp[index];
              this.SceneGroupId = resp[index].id;
              this.getSceneGroupAppliances();
            });
          } else {
            this.SceneGroupAppliancesData = [];
          }
        },
      });
    },
    //获取网点下设备
    getOrganProbeListData() {
      ajax.get({
        url: this.$API.getProbeChannelByOrganId + this.organId,
        success: (res) => {
          if(res.data!=null && res.data.length>0){
            this.prodlistdata = res.data.filter(data=>data.probeMoldCode !=34);
            this.allprodlistdata =res.data.filter(data=>data.probeMoldCode !=34);
          }
        },
        error: (err) => {
          // console.log(err)
          this.$message({
            message: err.message,
            type: "error",
          });
        },
      });
    },
    // 获取分组下的设备
    getSceneGroupAppliances() {
      let po_id = this.SceneGroupId;
      ajax.post({
        url: this.$API.sceneGroupDetailList + po_id,
        // data: { id: po_id },
        success: (response) => {
          const resp = response.data;
          this.SceneGroupAppliancesData = resp;
          let existsprod = [];
          if (this.SceneGroupAppliancesData) {
            this.SceneGroupAppliancesData.forEach((data) => {
              existsprod.push(data.channelId);
            });
          }
          this.oldproadvalue = [...existsprod]
          this.proadvalue = existsprod;
        },
      });
    },

    // table每行加上index
    tableRowClassName({ row, rowIndex }) {
      row.index = rowIndex;
    },
    // 点击
    handleCurrentChange(row) {
      this.currentSceneGroup = row;
      this.SceneGroupId = row.id;
      this.tableIndex = row.index;
      this.multipleManageSceneGroupSel = [];
      this.multipleAvailableSceneGroupSel = [];
      this.$nextTick(() => {
        this.getSceneGroupAppliances();
      });
    },

    // 新增控制组
    handleAddSceneGroup() {
      this.isAddNew = true;
      this.dialogSceneGroupVisible = true;
    },
    addSceneGroupSubmit(formName) {
      this.pojoSceneGroup.organId = this.organId;
      this.$refs[formName].validate((valid) => {
        if (valid) {
          ajax.post({
            url: this.$API.createSceneGroup,
            data: this.pojoSceneGroup,
            success: (response) => {
              if (response.success) {
                this.getSceneGroupData();
                this.dialogSceneGroupVisible = false;
                this.$message({
                  message: response.message,
                  type: "success",
                });
              }
            },
            error: (res) => {
              this.$message({
                message: res.message,
                type: "error",
              });
            },
          });
        }
      });
    },

    // 编辑控制组
    handleEditSceneGroup(row) {
      if (this.currentSceneGroup) {
        this.isAddNew = false;
        this.dialogSceneGroupVisible = true;
        this.$nextTick(() => {
          this.pojoSceneGroup = { ...row };
        });
      } else {
        this.$message({
          message: "请先选择要编辑的分组",
          type: "warning",
        });
      }
    },
    editSceneGroupSubmit(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          ajax.post({
            url: this.$API.editSceneGroup + this.pojoSceneGroup.id,
            data: this.pojoSceneGroup,
            success: (response) => {
              if (response.success) {
                this.getSceneGroupData();
                this.dialogSceneGroupVisible = false;
                this.$message({
                  message: response.message,
                  type: "success",
                });
              }
            },
            error: (res) => {
              this.$message({
                message: res.message,
                type: "error",
              });
            },
          });
        }
      });
    },

    // 删除组
    handleDeleteSceneGroup(row) {
      if (this.currentSceneGroup) {
        let po_id = row.id;
        deleteConfirm(this).then((res) => {
          if (res) {
            ajax.post({
              url: this.$API.delSceneGroup + po_id,
              success: (response) => {
                if (response.success) {
                  this.tableIndex = 0;
                  this.getSceneGroupData();
                  this.$message({
                    message: response.message,
                    type: "success",
                  });
                }
              },
              error: (response) => {
                this.$message({
                  message: response.message,
                  type: "error",
                });
              },
            });
          }
        });
      } else {
        this.$message({
          message: "请先选择要删除的组",
          type: "warning",
        });
      }
    },

    // 添加电器弹窗
    handleAddAreaAppliance() {
      this.dialogAddAreaVisible = true;
      this.checkList = [];
    },

    submitAddManageArea() {
      let self = this;
      if (this.proadvalue.length == 0) {
        this.$message({
          message: "请先选择探头",
          type: "warning",
        });
        return;
      }
      const binddata = this.prodlistdata
        .filter(item => this.proadvalue.includes(item.id))
        .filter(item => !this.oldproadvalue.includes(item.id))
        .map(({ id: channelId, channelName, probeId, probeGuid, probeMoldCode: probeType,targetCategoryId }) => ({
          channelId,
          channelName,
          probeId,
          probeGuid,
          probeName: '',
          probeType,
          groupId: this.SceneGroupId,
          targetCategoryId:targetCategoryId
        }));
      axios
        .post(this.$API.createSceneGroupDetailBatch, binddata)
        .then(function (res) {
          if (res.data.success) {
            self.$message({
              message: "新增成功",
              type: "success",
            });
            self.dialogAddAreaVisible = false;
          }
        });
    },

    // 重新获取绑定区域的数据
    reGetUserBindAreaData() {
      this.$refs.prodtransfer.clearQuery('left')
      // 清空右边搜索
      this.$refs.prodtransfer.clearQuery('right')
      if (this.SceneGroupId != null) {
        this.getSceneGroupAppliances();
      }
    },

    // 移除包含的区域和电器
    handleManageAreaChange(value) {
      this.multipleAreaAppSelection = value;
    },
    handleDeleteAreaAppliance() {

      let self = this;
      let selectionArr = this.multipleAreaAppSelection;
      let selResult = tableSelection(selectionArr, 0);
      if (selResult) {
        deleteConfirm(this).then((res) => {
          if (res) {
            let ids = selectionArr.map(item => item.id);
            axios.post(this.$API.delSceneGroupDetailBatch, ids).then(function (res) {
              if (res.data.success) {
                self.getSceneGroupAppliances();
                self.$message({
                  type: "success",
                  message: res.data.message,
                });
              }
            });
          }
        });
      }
    },
    handleChange(value) {
      let data = [...this.allprodlistdata];
      let areaid;
      if (value != 0) {
        areaid = value.slice(-1)[0];
        this.prodlistdata = data.filter((data) => data.areaId == areaid);
      } else {
        this.areaid = "";
        this.prodlistdata = data;
      }
    },

    // 重置表单
    resetForm() {
      this.$refs["pojoForm"].resetFields();
    },

    onSearchSubmit() {
      this.SceneGroupTableData = [...this.allSceneGroupTableData];
      this.SceneGroupTableData = this.SceneGroupTableData.filter((data) =>
        data.sceneGroupName.includes(this.Searchremark)
      );
    },
    searchEnter(e) {
      let keyCode = e.keyCode;
      if (keyCode == 13) {
        this.onSearchSubmit();
      }
    },

  },
};